package org.servlet;

import org.apache.log4j.Logger;
import org.domain.Account;
import org.domain.Cart;
import org.domain.Order;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class newOrderServlet extends HttpServlet {
    private static final String CART = "/WEB-INF/JSP/cart/Cart.jsp";
    private static final String NEW_ORDER = "/WEB-INF/JSP/order/NewOrderForm.jsp";
    private static Logger logger = Logger.getLogger(Class.class);
    Cart cart;
    Account account;
    Boolean authenticated;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        cart = (Cart) session.getAttribute("cart");
        account = (Account) session.getAttribute("account");
        authenticated = (Boolean) session.getAttribute("authenticated");

        if(account == null ||authenticated == false){
            request.setAttribute("msg", "Please Login in!");
            request.getRequestDispatcher(CART).forward(request, response);
        }
        else if(cart != null){
            Order order = new Order();
            order.initOrder(account, cart);
            session.setAttribute("order", order);
            logger.info(String.format("User (%s) Creat a New Form.", account.getUsername()));
            request.getRequestDispatcher(NEW_ORDER).forward(request, response);
        }
        else{
            request.setAttribute("msg", "Server Error");
            request.getRequestDispatcher(CART).forward(request, response);
        }
    }
}
